<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>

<body>

    <div class="layui-form layuimini-form">
        <div class="layui-form-item">
            <label class="layui-form-label required">新闻标题：</label>
            <div class="layui-input-block">
                <input type="text" name="title" lay-verify="required" id="title" lay-reqtext="新闻标题不能为空" placeholder="请输入新闻标题"
                    value="" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <!-- <label class="layui-form-label required">新闻内容：</label><br> -->
            <div id="editor" style="margin: 50px 0 50px 0">
                <!-- <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p> -->
            </div>
            <!-- <textarea id="text1" style="width:100%; height:200px;"></textarea> -->
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label required">封面：</label>
            <input type="hidden" name="img" value="" id="img">
            <div class="layui-input-block">
                <div class="layui-upload">
                    <button type="button" class="layui-btn" id="test1">上传图片</button>
                    <div class="layui-upload-list">
                        <img style="width: 100px;" class="layui-upload-img" id="demo1">
                        <p id="demoText">123</p>
                    </div>
                    <div style="width: 95px;">
                        <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                            <div class="layui-progress-bar" lay-percent=""></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                <button  class="layui-btn" lay-submit lay-filter="reset">重置</button>
                <!-- <button type="reset" class="layui-btn layui-btn-primary" id="reset">重置</button> -->
            </div>
        </div>
    </div>


    <!-- 注意， 使用富文本编辑器， 只需要引用 JS，无需引用任何 CSS ！！！-->
    <script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
    <script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
    <script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
    <script src="../../lib/jquery.cookie.min.js" charset="utf-8"></script>
    <script>
        layui.use(['upload', 'form', 'element', 'wangEditor'], function () {
            var form = layui.form,
                layer = layui.layer,
                // $ = layui.$,
                // $ = layui.jquery,
                upload = layui.upload,
                element = layui.element,
                wangEditor = layui.wangEditor;

            var adminUser = JSON.parse($.cookie("user"));


            // 发送请求来获取到token
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open("post", "http://localhost:8080/api/common/getUploadToken", false);
            xmlHttp.send();
            //手动获取到token
            var token = JSON.parse(xmlHttp.responseText).data;



            //自定一个token
            // var token = "6Q6kcBk0PIqZcfiwqKzGPoCqNwsYJ6f67ulZPuDG:o7MgXFWkXHirZkGSBWbYXmJecdM=:eyJzY29wZSI6ImFncmVlYWJsZSIsInJldHVybkJvZHkiOiJ7XCJidWNrZXRcIjpcIiQoZnNpemUpXCIsXCJrZXlcIjpcImh0dHA6Ly9yMjJ1NHdwZWIuaGQtYmt0LmNsb3VkZG4uY29tLyQoa2V5KVwiLFwiaGFzaFwiOlwiJChldGFnKVwifSIsImRlYWRsaW5lIjoxNjM2NDMxNDMxfQ==";

            var editor = new wangEditor('#editor');
            editor.customConfig.uploadImgServer = "http://up.qiniu.com";
            editor.customConfig.uploadImgParams = {
                token: token
                // x: 100
            }
            editor.customConfig.uploadFileName = 'file';
            editor.customConfig.pasteFilterStyle = false;
            editor.customConfig.uploadImgMaxLength = 5;
            editor.customConfig.uploadImgHooks = {
                // 上传超时
                timeout: function (xhr, editor) {
                    layer.msg('上传超时！')
                },
                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                customInsert: function (insertImg, result, editor) {
                    console.log(result);
                    let key = result.key;
                    if (key != null && key != "" && key != undefined) {
                        insertImg(key);

                    } else {
                        layer.msg("上传失败");
                    }
                }
            };
            editor.customConfig.customAlert = function (info) {
                layer.msg(info);
            };


            editor.create();


            // 配置alt选项
            editor.config.showLinkImgAlt = false
            // 配置超链接
            editor.config.showLinkImgHref = false



            //常规使用 - 普通图片上传
            var uploadInst = upload.render({
                elem: '#test1'
                , url: 'http://up.qiniu.com' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
                , data: { token: token }
                , accept: "images"
                , acceptMine: 'image/*'
                , size: 1024, //设置最大支持1MB文件上传
                before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#demo1').attr('src', result); //图片链接（base64）
                    });

                    element.progress('demo', '0%'); //进度条复位
                    layer.msg('上传中', { icon: 16, time: 0 });
                }
                , done: function (res) {
                    //如果上传失败
                    if (res.code > 0) {
                        return layer.msg('上传失败');
                    }


                    //上传成功的一些操作
                    $('#demo1').attr('src', res.key);

                    $('#img').val(res.key);   // 把图片地址写到 input 的隐藏域中
                


                    //……
                    $('#demoText').html(''); //置空上传失败的状态
                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
                //进度条
                , progress: function (n, elem, e) {
                    element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                    if (n == 100) {
                        layer.msg('上传完毕', { icon: 1 });
                    }
                }
            });

            form.on('submit(reset)',() => {
                console.log(111);
                $("#title").val("");
                editor.txt.html("");
                $("#img").val("");
                $("#demo1").attr('src',"");
                element.progress('demo', '0%'); //进度条复位

            })

            //监听提交
            form.on('submit(formDemo)', function (data) {

                let content = editor.txt.html();
                content = encodeURIComponent(content);

                //   console.log(data.field);
               

                $.post('http://localhost:8080/api/news/addNews',
                    {
                        title: data.field.title,
                        content: content,
                        admin_user_id: adminUser.id,
                        img:data.field.img

                    }
                    , function (result) {
                        if (result.code == 0) {
                            var iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);

                        } else {
                            layer.msg(result.msg);
                        }
                    }

                );

                return false;
            });



        });
    </script>
</body>

</html>